const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const {jwtSereKey,expiresIn} = require('../config')
const db = require('../mysql/db')





exports.registHandel = (req,res) => {
    const userinfo = req.body;
    if(!userinfo.username || !userinfo.password) {
        return res.send({
            status:1,
            message:'用户名或密码不能为空'
        })
    }
    if(userinfo.password !== userinfo.confirmPassword) {
        return res.send({
            status:1,
            message:'两次密码不一致'
        })
    }
    const sqlStr = 'select * from user where username=?'
    db.query(sqlStr,userinfo.username,(err,result)=> {
        if(err){
            return res.send({
                status:1,
                message:err.message
            })
        }
        if(result.length > 0) {
            return res.send({
                status:1,
                message:'用户名已存在'
            })
        }
        const str = 'insert into user set ?'
        userinfo.password = bcrypt.hashSync(userinfo.password,10)
        db.query(str,{username:userinfo.username,password:userinfo.password},(err,result)=> {
            if(err) {
                return res.send({
                    status:1,
                    message:err.message
                })
            }
            if(result.affectedRows !== 1){
                return res.send({
                    status:1,
                    message:'注册失败'
                })
            }
            res.send({
                status:0,
                message:'注册成功'
            })
        })
    })
}

exports.loginHandel = (req,res)=> {
    const userinfo = req.body;
    if(!userinfo.username ||!userinfo.password) {
        return res.cc('用户名或密码不能为空')
    }
    const sqlStr ='select * from user where username=?'
    db.query(sqlStr,userinfo.username,(err,result)=> {
        if(err){
           return res.cc(err)
        }
        if(result.length !== 1) {
            return res.cc('用户名不存在')
        }
        const comPareResult = bcrypt.compareSync(userinfo.password,result[0].password)
        if(!comPareResult) {
            return res.cc('密码错误')
        }
        const user = {...result[0],password:''}
        const tokenStr = jwt.sign(user,jwtSereKey,{expiresIn:expiresIn})
        res.send({
            status:0,
            message:'登录成功',
            token:'Bearer '+tokenStr,
            username:userinfo.username,
            id:user.id
        })  
    })
}